package com.pagepub.comm.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

public class FileUploadUtil {
	public static void uploadFile(File file, String fileName, String root) {
		File dir = new File(root);
		if(dir.exists()==false){
			dir.mkdir();
		}
		String path = root + "\\"+fileName;
		InputStream in = null;
		OutputStream out = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		File of = new File(path);
		if(of.exists()==false){
			try {
				of.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		int width = 0, height = 0;
		try {
			in = new FileInputStream(file);
			out = new FileOutputStream(of);
			
			bis = new BufferedInputStream(in);
			bos = new BufferedOutputStream(out);
			byte[] buf = new byte[(int) file.length()];
			int len = 0;
			while (((len = bis.read(buf)) != -1)) {
				bos.write(buf, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bos != null) {
					bos.close();
				}
				if (bis != null) {
					bis.close();
				}
			} catch (Exception e) {
				bos = null;
				bis = null;
			}
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (Exception e) {
				in = null;
				out = null;
			}
		}
	}
}
